import { NextRequest, NextResponse } from 'next/server'
import { upgradePlan } from '@/lib/limitChecker'
import { verifyToken } from '@/lib/authUtils'

export async function POST(request: NextRequest) {
  try {
    const token = request.headers.get('authorization')?.replace('Bearer ', '') ||
                  request.cookies.get('token')?.value
    
    if (!token) {
      return NextResponse.json({ error: '未授权访问' }, { status: 401 })
    }

    const decoded = await verifyToken(token)
    if (!decoded) {
      return NextResponse.json({ error: '无效的令牌' }, { status: 401 })
    }

    const { planType, durationMonths = 1 } = await request.json()
    
    if (!['basic', 'pro', 'enterprise'].includes(planType)) {
      return NextResponse.json({ error: '无效的套餐类型' }, { status: 400 })
    }

    await upgradePlan(decoded.userId, planType, durationMonths)
    
    return NextResponse.json({ 
      success: true, 
      message: `成功升级到${planType}套餐` 
    })
    
  } catch (error) {
    console.error('套餐升级失败:', error)
    return NextResponse.json(
      { error: '套餐升级失败' }, 
      { status: 500 }
    )
  }
}